package org.zhigong.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhigong.dao.RoleDao;
import org.zhigong.dao.RoleMenuDao;
import org.zhigong.entity.Menu;
import org.zhigong.entity.Role;
import org.zhigong.entity.RoleMenu;
import org.zhigong.service.RoleService;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleMenuDao roleMenuDao;

    public List<Role> getRoleList(Role role) {
        return roleDao.selectByPage(role);
    }

    public List<Role> getRoleListAll() {
        return roleDao.getAll();
    }

    public Role getRoleById(Long id) {
        return roleDao.queryById(id);
    }

    public Boolean addRole(Role role) {
        return (roleDao.insertRole(role) == 1) && (updateRoleMenu(role) >= 1) ;
    }

    public Boolean deleteRole(Long id) {
        roleMenuDao.deleteByRoleId(id);
        return   roleDao.deleteRole(id) == 1;
    }

    public Boolean updateRole(Role role) {
        roleMenuDao.deleteByRoleId(role.getId());
        updateRoleMenu(role);
        return roleDao.updateRole(role) == 1;
    }

    public List<Menu> getUnselectedMenu(Long id){
        return roleDao.getUnselectedMenu(id);
    }

    public int updateRoleMenu(Role role){
        List<Menu> menuList = role.getMenuList();
        if(menuList != null && menuList.size() > 0){
            List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
            for (Menu menu :
                    menuList) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menu.getId());
                roleMenuList.add(roleMenu);
            }
            return roleMenuDao.insertRoleMenu(roleMenuList);
        }
        return 0;
    }
}
